#!/bin/sh
#################################################################
#
#   Copyright 2010 Daniel Schopf
#             Institute for Theoretical and Applied Physics
#             University of Stuttgart, D-70550 Stuttgart, Germany
#             http://www.itap.physik.uni-stuttgart.de/
#
#################################################################
#
#   This file is part of potfit.
#
#   potfit is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   potfit is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with potfit; if not, see <http://www.gnu.org/licenses/>.
#
#################################################################

config_n=0;

while getopts 'n:?' OPTION
do
	case $OPTION in
		n) config_n="$OPTARG";
		;;
		?) printf "\nUsage: TODO\n";
		;;
	esac
done

shift $((OPTIND-1));

if [ ! -r $mgtools/INFO/CHTAB ]; then
	echo "Could not read CHTAB.";
	exit;
fi

if [ "`grep \#C $1`" == "" ]; then
	echo "Could not find chemical species in $1";
	exit;
fi

name=(`grep \#C $1 | sed -e 's/\#C //'`);
name_array=$( printf "%s," "${name[@]}" );

configs=`grep -n \#N $1 | wc -l`;
config_start=(`grep -n \#N $1 | sed s/:/\ /g | awk '{printf \$1" "}'`);
config_start[${configs}]=`wc -l $1 | awk '{print $1}'`;

if [ "$config_n" == "" ]; then
	echo "No configuration specified. Using first one." > /dev/stderr;
	config_n=1;
fi

if [ $config_n -gt $((configs-1)) ]; then
	echo "There are only $((configs-1)) configurations." > /dev/stderr;
	exit;
fi

echo "#F A 1 1 1 3 0 0";
echo "#C number type mass x y z";
sed -n ${config_start[$config_n]},${config_start[$((config_n+1))]}p $1 | grep \#\[X-Z\];
echo "## Generated by force2imd from `readlink -f $1` config $config_n";
echo "#E";
sed -n ${config_start[$config_n]},${config_start[$((config_n+1))]}p $1 | grep -v \# | awk -v name=$name_array '
BEGIN{
chfile=ENVIRON["mgtools"]"/INFO/CHTAB";
  while(getline<chfile){
    if($0 !~ /^ *\#/){sch[tolower($4)]=$2}
  }close(chfile);
  n_names=split(name,names,",")
}
{
 print i++,$1,sch[tolower(names[$1+1])],$2,$3,$4;
}'
